const http = require("http");
const routes = require("./module/routes");
const url = require("url");
const path = require("path");
const ejs = require("ejs");

http.createServer(function (req, res) {
  // 创建静态web服务
  routes.static(req, res, "static");

  // 路由
  let pathname = url.parse(req.url).pathname;
  pathname = pathname == '/' ? '/index.html' : pathname;
  let extname = path.extname(pathname);
  //如果有请求地址有后缀名的话让静态web服务去处理
  if (!extname) {
    // http://127.0.0.1:3000/news?page=2&id=1
    if (pathname == "/news") {
      // 获取get传值
      const query = url.parse(req.url, true).query;
      res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
      res.end(query.page);
    } else if (pathname == "/login") {
      // post 演示
      ejs.renderFile("./views/form.ejs", {}, (err, data) => {
        res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        res.end(data);
      })
    } else if (pathname == "/doLogin") {
      // 获取 post 传值
      let postData = "";
      req.on("data", (chunk) => {
        postData += chunk;
      })
      req.on("end", () => {
        console.log(postData);
        res.end(postData);
      })

    } else {
      res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
      res.end("404这个页面不存在");
    }
  }
}).listen(3000);

console.log("Server running at http://127.0.0.1:3000/");